﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.Util;
using AcctrueWMS.Foundation.Web;
using Microsoft.Reporting.WebForms;
using System.Data;
using AcctrueWMS.Foundation.Web.Modules;

namespace AcctrueWMS.Foundation.Render
{
    public class CommonRender
    {
        private static Regex btn_render_reg = new Regex(@"(?<name>[\w|\d]+)\s*=\s*(?<value>.*?);");
        DataModelManager modelManager = new DataModelManager();
        TemplateManager templateManager = new TemplateManager();

        public CommonRender(IDataModelContext context)
        {
            this.context = context;
        }
        private IDataModelContext context;
        public IDataModelContext Context
        {
            get
            {
                return context;
            }
        }
        public string RenderButton(string expr)
        {
            StringBuilder sb = new StringBuilder();
            System.Collections.Generic.Dictionary<string, string> nvpair = new System.Collections.Generic.Dictionary<string, string>();
            foreach (Match m in btn_render_reg.Matches(expr))
            {
                string name = m.Groups["name"].Value;
                string value = m.Groups["value"].Value;
                nvpair.Add(name, value);
            }
            #region 拼写  html 生成对应的 Button
            sb.Append(@"<input type='button' class='imgBtn' onmouseover=this.className='btn_yellow' onmouseout=this.className='imgBtn'  ");
            string id = "";

            //生成Button ID属性
            if (nvpair.ContainsKey("id"))      //已为Button指定ID属性
            {
                id = nvpair["id"];
                sb.Append(" id='" + nvpair["id"] + "' ");
                sb.Append(" " + ProcessPermission(nvpair["id"]) + " ");
                nvpair.Remove("id");
            }
            else
            {
                if (nvpair.ContainsKey("actionType"))    //根据Button类型生成控件ID
                {
                    id = nvpair["actionType"] + Guid.NewGuid().ToString();
                    sb.Append("id='" + id + "'");

                    if (nvpair["actionType"] == "outExcel" || nvpair["actionType"] == "close")
                    {

                    }
                    else
                    {
                        string controlID = GetControlIDByActionType(nvpair["actionType"]);
                        string disabled = ProcessPermission(controlID);
                        sb.Append(disabled);
                    }
                }
                else
                {
                    id = "search" + Guid.NewGuid().ToString();   //为查询Button生成ID
                    sb.Append("id='" + id + "'");

                    string controlID = GetControlIDByActionType("search");
                    string disabled = ProcessPermission(controlID);
                    sb.Append(disabled);
                }
            }

            //生成Butt 类型
            string actionType = "";
            if (!nvpair.ContainsKey("actionType"))
            {
                actionType = "search";
                sb.Append("actionType='search'");

                string controlID = GetControlIDByActionType("search");
                string disabled = ProcessPermission(controlID);
                sb.Append(disabled);
            }

            //生成Button Value
            if (nvpair.ContainsKey("text"))
            {
                sb.Append("value='" + nvpair["text"] + "'");
                nvpair.Remove("text");
            }
            else if (nvpair.ContainsKey("actionType"))
            {
                actionType = nvpair["actionType"];
                sb.Append("actionType='" + nvpair["actionType"] + "'");
                sb.Append("value='" + GetValueByActionType(nvpair["actionType"]) + "'");
                nvpair.Remove("actionType");
            }
            else
            {
                sb.Append("value='查询'");
            }

            //为Button绑定事件
            string clientMethod = string.Empty;
            string serverMethod = string.Empty;

            if (nvpair.ContainsKey("clientMethod"))
            {
                clientMethod = nvpair["clientMethod"];
                sb.Append(" clientMethod='" + nvpair["clientMethod"] + "' ");
                nvpair.Remove("clientMethod");
            }
            if (nvpair.ContainsKey("serverMethod"))
            {
                serverMethod = nvpair["serverMethod"];
                nvpair.Remove("serverMethod");
            }
            if (nvpair.Count > 0)
            {
                foreach (KeyValuePair<string, string> kev in nvpair)
                {
                    sb.Append("  " + kev.Key + "=" + kev.Value + "  ");
                }
            }
            if (actionType == "search")  //查询按钮事件绑定
            {
                sb.Append(" onclick=\"wmsCommon.search()\"");
            } 
            else if (actionType == "print")    // 打印按钮事件绑定
            {
                if (string.IsNullOrEmpty(nvpair["clientMethod"]) && string.IsNullOrEmpty(nvpair["serverMethod"]))
                sb.Append(" onclick=\"wmsCommon.print()\"");
            }
            sb.Append("/>");

            if (!string.IsNullOrEmpty(clientMethod))
            {
                ///绑定脚本
                sb.Append("<script>");
                sb.Append("jQuery('#" + id + "').unbind();");
                sb.Append("    jQuery('#" + id + "').bind('click',function(){if(" + clientMethod + "){" + serverMethod + ";}})");
                sb.Append("</script>");
            }

            #endregion
            return sb.ToString();
        }

        private string GetValueByActionType(string actionType)
        {
            string value = "";
            switch (actionType)
            {
                case "new":
                    value = "新增";
                    break;
                case "audit":
                    value = "审核";
                    break;
                case "delete":
                    value = "删除";
                    break;
                case "modify":
                    value = "修改";
                    break;
                case "save":
                    value = "保存";
                    break;
                case "print":
                    value = "打印";
                    break;
                case "search":
                default:
                    value = "查询";
                    break;
            }
            return value;
        }



        private int GetMaskNoByActionType(string actionType)
        {
            int maskNo = -1;
            switch (actionType)
            {
                case "new":
                    maskNo = 5;
                    break;
                case "audit":
                    maskNo = 7;
                    break;
                case "delete":
                    maskNo = 2;
                    break;
                case "modify":
                    maskNo = 6;
                    break;
                case "save":
                    maskNo = 1;
                    break;
                case "search":
                    maskNo = 4;
                    break;
                default:
                    maskNo = -1;
                    break;
            }
            return maskNo;
        }

        private string GetControlIDByActionType(string actionType)
        {
            string controlID = "";
            switch (actionType)
            {
                case AccRenderBtnType.NEW:
                    controlID = AccRenderBtnId.BTN_Add_ID;
                    break;
                case AccRenderBtnType.AUDIT:
                    controlID = AccRenderBtnId.BTN_AUDIT_ID;
                    break;
                case AccRenderBtnType.DELETE:
                    controlID = AccRenderBtnId.BTN_DEL_ID;
                    break;
                case AccRenderBtnType.MODIFY:
                    controlID = AccRenderBtnId.BTN_MODIFY_ID;
                    break;
                case AccRenderBtnType.SAVE:
                    controlID = AccRenderBtnId.BTN_SAVE_ID;
                    break;
                case AccRenderBtnType.SEARCH:
                    controlID = AccRenderBtnId.BTN_SEARCH_ID;
                    break;
                case AccRenderBtnType.SUBMIT:
                    controlID = AccRenderBtnId.BTN_SUBMIT_ID;
                    break;
                case AccRenderBtnType.ROLLBACK:
                    controlID = AccRenderBtnId.BTN_ROLLBACK_ID;
                    break;
                case AccRenderBtnType.BACKOUT:
                    controlID = AccRenderBtnId.BTN_BACKOUT_ID;
                    break;
                case AccRenderBtnType.ALLOCATE:
                    controlID = AccRenderBtnId.BTN_ALLOCATE_ID;
                    break;
                case AccRenderBtnType.SENDING:
                    controlID = AccRenderBtnId.BTN_SENDING_ID;
                    break;
                case AccRenderBtnType.AJUSTING:
                    controlID = AccRenderBtnId.BTN_AJUSTING_ID;
                    break;
                case AccRenderBtnType.STATION_AUTHORIZE:
                    controlID = AccRenderBtnId.BTN_STATION_AUTHORIZE_ID;
                    break;
                case AccRenderBtnType.DEPOT_AUTHORIZE:
                    controlID = AccRenderBtnId.BTN_DEPOT_AUTHORIZAE_ID;
                    break;

                case AccRenderBtnType.PEINR:
                    controlID = AccRenderBtnId.BTN_PRINT_ID;
                    break;
                default:
                    controlID = actionType;
                    break;
            }
            return controlID;
        }

        public string RenderButton()
        {

            return RenderButton("");
        }

        //private string GenerateSearchScript(string id)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("<script>");
        //    sb.Append("    jQuery('#" + id + "').bind('click',function () {");
        //    sb.Append("   var queryStr = GenerateQueryStr();");
        //    sb.Append("var location=document.location.href.split('?')[0];");
        //    sb.Append("location+='?model='+modelName+'&temp='+wmsCommon.getQueryValue('temp')+'&con='+escape(GetQueryCon())+'&order='+escape(wmsCommon.getQueryValue('order'))+'&querycon='+escape(queryStr)+'&pagesize='+pageSize+'&currpage=0';");
        //    sb.Append("document.location.href=location;");
        //    //    sb.Append("return true;");
        //    sb.Append(" });");
        //    sb.Append("</script>");
        //    return sb.ToString();
        //}
        private string GenerateDetailButton(string btnName, System.Collections.Generic.Dictionary<string, string> nvpair)
        {
            StringBuilder sb = new StringBuilder();

            if (btnName.Contains("$"))
            {
                sb.Append(" value='" + GetTypeName(btnName.Split('$')[1]) + "' id='" + btnName + "'");
            }
            sb.Append(" " + ProcessPermission(btnName) + " ");
            if (nvpair.ContainsKey("method"))
            {
                sb.Append(" method='" + nvpair["method"] + "'");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 控件是否有权限
        /// </summary>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static bool HasPermission(string url, string controlID)
        {
            bool result = false;
            SystemUser user = Runtime.CurrentUser;

            //内置用户有所有权限
            if (user.UserName == "admin" || user.IsAdmin)
            {
                return true;
            }

            //如果此链接有默认权限则直接返回
            ModuleInfo module = Runtime.ModuleManager.GetModuleByUrl(url);
            string defaultPrivilege = Runtime.PermissionManager.HasPermission(url, module);
            if (defaultPrivilege == "all")
                return true;

            if (user != null)
            {
                #region oldCode
                //string[] roleCodes = user.RoleCodes.Split(',');
                //foreach (string roleCode in roleCodes)
                //{
                //    List<RoleModule> roleList = Runtime.ModuleAuthorityManager.GetAuthorityMaskCode(roleCode);
                //    foreach (RoleModule module in roleList)
                //    {
                //        string moduleName=Runtime.ModuleManager.GetModuleInfoByWBS(module.ModuleWBS).ModuleName;
                //        int actionMask=module.PrivilegeMask;
                //        Runtime.PermissionManager.AddPermission(moduleName, actionMask);
                //    }
                //    if (Runtime.ModuleManager.GetRootModule() != null)
                //    {
                //        result = Runtime.PermissionManager.HasPermission(url, controlID);
                //    }
                //    if (result)
                //        break;
                //    else continue;
                //}

                #endregion                
                result = Runtime.PermissionManager.HasPermission(url, controlID, user.RoleCodes, module);
            }



            return result;
        }

        /// <summary>
        /// 控件是否有权限
        /// </summary>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public string ProcessPermission(string controlID)
        {
            if (!HasPermission(this.Context.CurrentUrl, controlID))
            {
                //return string.Empty;
                return " disabled='true' ";
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 生成明细增删按钮
        /// </summary>
        /// <param name="btnName"></param>
        /// <returns></returns>
        private string GenerateDetailButton(string btnName)
        {
            StringBuilder sb = new StringBuilder();

            if (btnName.Contains("$"))
            {
                sb.Append(" value='" + GetTypeName(btnName.Split('$')[1]) + "' id='" + btnName + "'");
            }
            sb.Append(" " + ProcessPermission(btnName) + " ");
            return sb.ToString();
        }
        private string GetTypeName(string type)
        {
            string typeName = string.Empty;
            switch (type)
            {
                case "add":
                case "new":
                    typeName = "新增";
                    break;
                case "del":
                    typeName = "删除";
                    break;
                default:
                    break;
            }
            return typeName;

        }

        public string RenderPaging(DataModel model, ModelTemplate template)
        {
            if (model == null)
                return string.Empty;
            else
            {
                HttpRequest request = HttpContext.Current.Request;
                NameValueCollection queryString = CopyQueryString(request.QueryString);
                if (queryString["pagesize"] == null)
                    queryString.Add("pagesize", template.Meta.ContainsKey("pagesize") ? template.Meta["pagesize"] : "15");
                if (queryString["currpage"] == null)
                    queryString.Add("currpage", "0");
                int cnt = model.TotalCount;
                int pageSize = int.Parse(queryString["pagesize"]);
                int pageIndex = int.Parse(queryString["currpage"]);
                int pageNum = (cnt % pageSize == 0) ? (cnt / pageSize) : (cnt / pageSize + 1);
                StringBuilder sb = new StringBuilder();

                sb.Append("<table ><tr><td style='text-align:left'><div style='font-size:12px;font-weight:bolder;'>");
                sb.Append("【共");
                sb.Append(string.Format("<span id='totalCount'>{0}</span>条记录】", cnt));
                sb.Append("【第");
                sb.Append(string.Format("<span id='currpageIndex'>{0}</span>页 / ", pageIndex + 1));
                sb.Append("共");
                sb.Append(string.Format("<span id='totalPage'>{0}</span>页】", pageNum));
                sb.Append("</div></td>");

                sb.Append("<td aligh='right' style='width:265px;'><div id='Pagination' class='pagination'>");
                //页数大于1时，才显示分页
                if (pageNum > 1)
                {                          
                    if (pageIndex > 0)
                    {
                        queryString["currpage"] = "0";      
                        sb.Append(string.Format("<a class='imgBtn'  onmouseover=this.className='btn_yellow' onmouseout=this.className='imgBtn'  href=\"{0}\">|<首页</a>", BuildNewUrl(request, queryString)));

                        queryString["currpage"] = (pageIndex - 1).ToString();
                        sb.Append(string.Format("<a  class='imgBtn' onmouseover=this.className='btn_yellow' onmouseout=this.className='imgBtn'  href=\"{0}\"><<上一页</a>", BuildNewUrl(request, queryString)));
                    }
                    else
                    {
                        sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">|<首页</a>"));
                        sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\"><<上一页</a>"));
                    }
                    if (pageIndex < pageNum - 1)
                    {
                        queryString["currpage"] = (pageIndex + 1).ToString();
                        sb.Append(string.Format("<a  class='imgBtn' onmouseover=this.className='btn_yellow' onmouseout=this.className='imgBtn' href=\"{0}\">下一页>></a>", BuildNewUrl(request, queryString)));

                        queryString["currpage"] = (pageNum - 1).ToString();
                        sb.Append(string.Format("<a class='imgBtn' onmouseover=this.className='btn_yellow' onmouseout=this.className='imgBtn'  href=\"{0}\">末页>|</a>", BuildNewUrl(request, queryString)));
                    }
                    else
                    {
                        sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">下一页>></a>"));
                        sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">末页>|</a>"));
                    }
               
                }
                else  /// 如果没有分页，则把所有翻页按钮置灰
                {
                    sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">|<首页</a>"));
                    sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\"><<上一页</a>"));
                    sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">下一页>></a>"));
                    sb.Append(string.Format("<a  class='imgBtn' disabled  href=\"#\">末页>|</a>"));
                }
                sb.Append("</div></td></tr></table>");
                return sb.ToString();
            }
        }
        /// <summary>
        /// 生成JQuery分页控件
        /// </summary>
        /// <returns></returns>
        public string RenderPaging(DataModel model)
        {
            string templateName = HttpContext.Current.Request.QueryString["temp"];
            ModelTemplate t = templateManager.LoadTemplate(templateManager.GetTemplateFile(templateName));
            return RenderPaging(model, t);
        }
        private string BuildNewUrl(HttpRequest request, NameValueCollection queryString)
        {
            string querystr = string.Empty;
            foreach (string key in queryString.Keys)
                querystr += string.Format("{0}={1}&", key, HttpUtility.UrlEncode(queryString[key]));
            int lastIndex = querystr.LastIndexOf('&');
            if (lastIndex == querystr.Length - 1)
                querystr = querystr.Remove(lastIndex);
            return string.Format("{0}?{1}", request.FilePath, querystr);
        }
        /// <summary>
        /// 复制查询字符串
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private NameValueCollection CopyQueryString(NameValueCollection queryString)
        {
            NameValueCollection collection = new NameValueCollection();
            foreach (string key in queryString.Keys)
                collection.Add(key, queryString[key]);
            return collection;
        }
        /// <summary>
        /// 生成Checkbox
        /// </summary>
        /// <returns></returns>
        public string RenderCheckBox(string id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<input type='checkbox' id='" + id + "'/>");
            return sb.ToString();
        }


        /// <summary>
        /// 生成报表
        /// </summary>
        /// <param name="model">模板名称</param>
        /// <param name="rdlc">rdlc文件名</param>
        /// <returns></returns>
        public string RenderReport(DataModel model, string rdlc)
        {
            return RenderReport(model, rdlc, "true","");
        }


        /// <summary>
        /// 生成报表
        /// </summary>
        /// <param name="model">模板名称</param>
        /// <param name="rdlc">rdlc文件名</param>
        /// <param name="showReportHeader">是否显示头</param>
        /// <returns></returns>
        public string RenderReport(DataModel model, string rdlc, string showReportHeader,string  exportFileName)
        {
            //TextWriter tw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(tw);

            //ReportViewer rv = new ReportViewer();
            //rv.ID = model.Name;
            //rv.EnableViewState = true;
            //System.Data.DataTable dt = model.ToDataTable();
            //ReportDataSource dataSource = new ReportDataSource("dsStockInfoMaterials", model.ToDataTable());
            //rv.LocalReport.ReportPath = HttpContext.Current.Server.MapPath(rdlcPath);//"~/Report/rptStockInfoMaterials.rdlc");
            //rv.LocalReport.DataSources.Clear();
            //rv.LocalReport.DataSources.Add(dataSource);
            //rv.RenderControl(htw);

            System.Data.DataTable dt = model.ToDataTable();
            //将报表数据加入缓存而不是Session中，节约内存，提高性能
            Runtime.Cache[rdlc] = dt;

            string returnValue = "<IFRAME id='reportviewerframe' frameborder='0' src='";
            returnValue += "Exec/Report.aspx?rdlc=";
            returnValue += rdlc;
            returnValue += "&showReportHeader=";
            returnValue += showReportHeader;
            returnValue += "&exportFileName=";
            returnValue += exportFileName;
            returnValue += "' width=100% height= 98% scrolling=yes></IFRAME>";

            return returnValue;
        }


        ///// <summary>
        ///// 生成报表
        ///// </summary>
        ///// <param name="model">模板名称</param>
        ///// <param name="rdlc">rdlc文件名</param>
        ///// <param name="showReportHeader">是否显示头</param>
        ///// <returns></returns>
        //public string RenderReport(DataTable dt, string rdlc, string showReportHeader)
        //{
            
        //    //将报表数据加入缓存而不是Session中，节约内存，提高性能
        //    Runtime.Cache[rdlc] = dt;

        //    string returnValue = "<IFRAME id='reportviewerframe' frameborder='0' src='";
        //    returnValue += "Exec/Report.aspx?rdlc=";
        //    returnValue += rdlc;
        //    returnValue += "&showReportHeader=";
        //    returnValue += showReportHeader;
        //    returnValue += "' width=100% height= 95%></IFRAME>";

        //    return returnValue;
        //}
    }
}
